// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;
using System.Data;

namespace SnapObjects.Data
{
    internal class DynamicDataModelBinder : DataModelBinder<DynamicModel>
    {
        public DynamicDataModelBinder(
            IList<DbColumnInfo> columnSchema, ITypeMapper typeMapper)
            : base(new DataModelBinding(columnSchema, typeMapper))
        {
            _factory = ModelFactoryFactory.Create(this.ModelBinding.ModelProperties);
        }

        protected override void SetValue(DynamicModel model, int index, object value)
        {
            model.SetValue(index, value);
        }

        protected override void SetValue(DynamicModel model, string name, object value)
        {
            model.SetValue(name, value);
        }

        public override DynamicModel BindModel(IDataReader dataReader)
        {
            var model = this.ModelFactory.Create();

            foreach (var binding in this.ModelBinding.Properties)
            {
                var value = this.GetDbValue(dataReader, binding);

                this.SetValue(model, binding.Property.Name, value);
            }

            return model;
        }
    }
}
